import { Button, Col, message, Space, Table } from 'antd';
import { Ref, useCallback, useContext, useImperativeHandle, useRef, useState } from 'react';
import { UserManageContext, UserOtherHandleContext, useUserOtherHandleRendecer } from '../hooks';
import { IUserColumnsOpt, IUserRightTableContentView } from '../type';
import cls from 'classnames';
import { getUserTableColumns } from './PageConfig';
import { PlusOutlined, TableOutlined, AppstoreAddOutlined } from '@ant-design/icons';
import ChangeColumns from '@/components/ActionButton/components/ChangeColumns';
import { IOneModalRef } from '@/pages/type';
import React from 'react';
import { commonPageSizeOptions, showTotalInfo } from '@/common/constVariable';
import { UseAddOrEditModal } from './UseAddOrEditModal';
import { useRequest } from 'umi';
import { resetPwdUser, switchUserIsOpen } from '../hooks/userManageTableServices';
import { UserCofigModal } from './UserCofigModal';
import { UserSetPosDataModal } from './UserSetPosDataModal';
import { UserDetailInfoDraw } from './UserDetailInfoDraw';
import { UserRightTableTitleView } from './UserRightTableTitleView';
import { OpenRoleModal } from './OpenRoleModal';

export const UserRightTableContentView = React.forwardRef(
  (
    {
      userTableData, //表格数据
      userTableLoading, //表格loading
    }: IUserRightTableContentView,
    ref,
  ) => {
    const { userFixCls, curRes, leftTreeType, rightTablePagination, reloadRightTable, searchFormValues, userManDispatch, rightRoladTabieUser } = useContext(
      UserManageContext,
    );
    const [visible, setVisible] = useState(false);
    const changeColumnRef: Ref<IOneModalRef> = useRef(null); //弹框的ref  IOneModalRef 为公共组件 oneModal 的 类型
    const userRightTieleRef = React.useRef<Record<string, any>>();

    /** 是否打开授权弹框 */
    const [openRoleModal, setOpenRoleModal] = useState<Record<string, any>>({
      showModal: false,
      checkRowInfo: {},
    });

    // 获取表格当前的reducer
    const {
      userOthDispatch,
      currentStep,
      secopeLeftSearValue,
      twoLeftExpandedKeys,
      twoAutoExpandParent,
      twoLeftSelectKeys,
      twoLeftSelectRows,
      secopeRightSearValue,
      userDetailSearchValue,
    } = useUserOtherHandleRendecer();

    // ref
    useImperativeHandle(ref, () => ({
      userAddEditForm: leftCheckReloadRight,
    }));

    // 表格选择框
    const [checkedRowKeys, setCheckedRowKeys] = useState<string[]>([]);

    // 是否打开弹框
    const [addEditModal, setAddEditModal] = useState<boolean>(false);
    const [onCheckRows, setOnCheckRows] = useState<any>(); //保存点击行的数据

    // 是否打开设置岗位弹框
    const [isShowSetPos, setIsShowSetPos] = useState<boolean>(false);
    const [posModalType, setPosModalType] = useState<string>('');
    const isOpenSetPos = (isOpen: boolean, modalType: string) => {
      setIsShowSetPos(isOpen);
      setPosModalType(modalType);
    };

    const [showConfimModal, setShowConfimModal] = useState<boolean>(false); //禁用状态提示框
    // 判断是否是所属岗位都被禁用
    const [modalTip, setModalTip] = useState<string>('');
    // 禁用状态提示框回调
    const openConfimModal = (isModal: boolean, checkRows: any, resMsg: string) => {
      setShowConfimModal(isModal);
      if (isModal) {
        setModalTip(resMsg);
        setOnCheckRows(checkRows);
      }
    };

    // 是否打开详情抽屉
    const [isShowInfoDraw, setIsShowInfoDraw] = useState<boolean>(false);
    const infoDrawCall = (isShow: boolean, resObj) => {
      setOnCheckRows(resObj);
      setIsShowInfoDraw(isShow);
    };

    let onOptClick: IUserColumnsOpt = {
      // 编辑
      onEditAdd: (recObj: any) => {
        setOnCheckRows(recObj);
        setAddEditModal(true);
      },

      // 修改状态
      onChangeIsOpen: (checked, record) => {
        if (checked) {
          checkFalseIsOpen?.run(checked, record);
        } else {
          openConfimModal(true, record, '禁用后该用户将无法进行登录，是否确认禁用？');
        }
      },
      // 设施岗位
      setPositionFunc: (resObj: any) => {
        setOnCheckRows(resObj);
        isOpenSetPos(true, 'SETPOS');
      },

      // 重置密码
      reloadUserPwo: (resObj: any) => {
        let params: any = {
          id: resObj?.id,
          versionNum: resObj?.versionNum,
        };
        allotPosService?.run(params);
      },

      // 查看详情
      seeDetailView: (record: Record<any, any>) => {
        infoDrawCall(true, record);
      },

      // 授权
      onPosOption: (resObj) => {
        setOpenRoleModal({
          showModal: true,
          checkRowInfo: resObj,
        });
      },
    };

    // 调用设置岗位接口
    const allotPosService = useRequest(
      (payload: any) => {
        return resetPwdUser({
          ...payload,
        });
      },
      {
        manual: true,
        onSuccess: (res) => {
          if (res && res?.msgFlag) {
            openConfimModal(true, {}, res?.msg);
            rightRoladTabieUser();
          } else {
            message.error(res?.msg);
          }
        },
      },
    );

    // 调用修改状态的按钮
    const checkFalseIsOpen = useRequest(
      (openState: boolean, recObj: any) => {
        let params = {
          versionNum: recObj?.versionNum,
          id: recObj?.id,
          isOpen: openState ? 1 : 0,
        };
        return switchUserIsOpen(params);
      },
      {
        manual: true,
        onSuccess: (res: any) => {
          if (res && res?.versionFlag) {
            if (res && res?.msgFlag) {
              message?.success(res?.msg);
              rightRoladTabieUser();
            } else {
              openConfimModal(true, {}, res?.msg);
            }
          } else {
            message?.error(res?.msg);
          }
        },
      },
    );

    // 表格行操作
    const [userColumns, setUserColumns] = useState(getUserTableColumns(curRes, onOptClick));
    // 修改显示列
    const changeColumns = useCallback(
      (columns) => {
        setUserColumns(columns);
      },
      [userColumns],
    );

    // 关闭显示列
    const closeShowCloumns = () => {
      setVisible(false);
    };

    // 打开显示列
    const openShowCloumns = () => {
      setVisible(true);
    };
    // 确认修改显示列
    const onOKCloumns = (columns: any[]) => {
      if (columns) {
        changeColumns(columns);
        changeColumnRef?.current?.onModalCancel();
      }
    };

    // 修改显示列
    let showColumns = React.useMemo(() => {
      let newColumns: any = [];
      userColumns.forEach((i: any) => {
        if (i?.visible) {
          newColumns.push({
            ...i,
            showSorterTooltip: false,
          });
        }
      });
      return newColumns;
    }, [userColumns]);

    // 分页页数 和数据条数改变
    const handlePaginationChange = (page: number, pageSize: number) => {
      let params = {
        ...leftTreeType, //左侧树节点点击存的参数
        ...rightTablePagination, //右侧分页参数
        ...searchFormValues, //右侧表单参数
        page: page,
        rows: pageSize,
      };
      userManDispatch({
        //保存分页器参数
        type: 'user-rightTablePagination',
        payload: { ...rightTablePagination, page: page, rows: pageSize },
      });

      // 获取用户数据
      reloadRightTable(params);
    };

    // 禁用资源
    const chanageSwitch = (check: boolean, resObj: any) => {
      checkFalseIsOpen?.run(check, resObj);
    };

    // 表格选中操作
    const tableChange = (selectedRowKeys: any, selectedRows: any, type?: string) => {
      if (type == 'rowClick') {
        let checkIDS: string[] = [...checkedRowKeys];
        if (checkIDS?.includes(selectedRowKeys)) {
          checkIDS = checkIDS?.filter((item: any) => item != selectedRowKeys);
        } else {
          checkIDS?.push(selectedRowKeys);
        }
        let idsCopy = [...new Set(checkIDS)];
        setCheckedRowKeys(idsCopy);
      } else {
        setCheckedRowKeys(selectedRowKeys);
      }
    };

    // 批量设置岗位
    const batchAllotPosition = () => {
      if (checkedRowKeys?.length > 0) {
        setOnCheckRows({});
        isOpenSetPos(true, 'ALLPOS');
      } else {
        message.warning('请至少选择一位用户！');
      }
    };

    // 左侧点击 清空右侧搜索表单的数据
    const leftCheckReloadRight = () => {
      userRightTieleRef?.current?.reloadSearchForm();
    };

    return (
      <>
        <UserOtherHandleContext.Provider
          value={{
            userOthDispatch, //表格的派发方法
            currentStep, //新增弹框步数
            secopeLeftSearValue, //第二步左边搜索的值
            twoLeftExpandedKeys, //搜索节点的父ID
            twoAutoExpandParent, //是否自动展开
            twoLeftSelectKeys, //左侧卡片树 选中的 key
            twoLeftSelectRows, //左侧卡片树选中的 rows
            secopeRightSearValue, //第二步右侧搜索值
            userDetailSearchValue, //详情里岗位卡片搜索值
          }}
        >
          <Col span={18} className={cls(userFixCls + 'user-col')}>
            <div className={userFixCls + 'col-div-box'}>
              <UserRightTableTitleView ref={userRightTieleRef} />

              {/* <div className={userFixCls + 'col-div-box'}> */}
              <div className={userFixCls + 'tableRight-contentTitle'}>
                <Space>
                  {curRes['/userController/add'] && (
                    <Button
                      type={'primary'}
                      icon={<PlusOutlined />}
                      onClick={() => {
                        setOnCheckRows({});
                        setAddEditModal(true);
                      }}
                    >
                      添加
                    </Button>
                  )}
                  {curRes['/userController/batchAllotPosition'] && (
                    <Button
                      type={'primary'}
                      icon={<AppstoreAddOutlined />}
                      onClick={batchAllotPosition}
                      onMouseOut={(event: any) => {
                        event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
                      }}
                    >
                      批量设置岗位
                    </Button>
                  )}
                </Space>

                <Button icon={<TableOutlined />} onClick={openShowCloumns}>
                  显示列
                </Button>
              </div>
              <div className={userFixCls + 'tableRight-content'}>
                <div className={cls('list-table')}>
                  <Table
                    size="small"
                    columns={showColumns}
                    bordered
                    loading={userTableLoading || checkFalseIsOpen?.loading}
                    dataSource={userTableData?.rows}
                    scroll={{ x: 1200, y: 'true' }}
                    rowKey={(record: any) => {
                      return record?.id;
                    }}
                    pagination={{
                      showQuickJumper: true,
                      showSizeChanger: true,
                      pageSizeOptions: commonPageSizeOptions,
                      showTotal: showTotalInfo,
                      onChange: handlePaginationChange,
                      pageSize: rightTablePagination?.rows,
                      current: rightTablePagination?.page,
                      total: userTableData?.total,
                    }}
                    rowSelection={{
                      type: 'checkbox',
                      selectedRowKeys: checkedRowKeys,
                      onChange: tableChange as any,
                      getCheckboxProps: (record: any) => {
                        if (record?.isOpen == 1) {
                          return {
                            disabled: false,
                          };
                        } else {
                          return {
                            disabled: true,
                          };
                        }
                      },
                    }}
                    onRow={(record: any) => {
                      return {
                        onClick: (event) => {
                          event.stopPropagation();
                          tableChange(record?.id, record, 'rowClick');
                        },
                      };
                    }}
                  />
                </div>
              </div>
              {/* </div> */}
              {visible && <ChangeColumns onClose={closeShowCloumns} onOk={onOKCloumns} columnsList={userColumns} ref={changeColumnRef} />}

              {/* 新增编辑弹框 */}
              {addEditModal && (
                <UseAddOrEditModal
                  onClose={() => {
                    setAddEditModal(false);
                  }}
                  checkRows={onCheckRows}
                  isShowModal={addEditModal}
                />
              )}

              {/* 设置岗位弹框 */}
              {isShowSetPos && (
                <UserSetPosDataModal
                  onClose={() => {
                    isOpenSetPos(false, posModalType);
                  }}
                  checkRows={onCheckRows}
                  isShowModal={isShowSetPos}
                  posModalType={posModalType}
                  checkedRowKeys={checkedRowKeys}
                />
              )}

              {/* 报错提示弹框 */}
              {showConfimModal && (
                <UserCofigModal
                  visible={showConfimModal}
                  onClose={() => {
                    openConfimModal(false, {}, '');
                  }}
                  chanageSwitch={chanageSwitch}
                  tableRowObj={onCheckRows}
                  modalTip={modalTip}
                />
              )}
            </div>
          </Col>

          {/* 详情抽屉 */}
          <UserDetailInfoDraw
            onRowDetail={onCheckRows}
            visible={isShowInfoDraw}
            onCloceDrawer={() => {
              infoDrawCall(false, {});
            }}
          />

          {/* 打开授权弹框 */}
          {openRoleModal?.showModal && (
            <OpenRoleModal
              onClose={() => {
                setOpenRoleModal({
                  showModal: false,
                  checkRowInfo: {},
                });
              }}
              checkRowInfo={openRoleModal?.checkRowInfo}
              openModal={openRoleModal?.showModal}
            />
          )}
        </UserOtherHandleContext.Provider>
      </>
    );
  },
);
